package com.atguigu.day08;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.*;
import org.apache.kafka.clients.consumer.ConsumerConfig;

public class Flink04_TableAPI_Connect_Kafka {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 3.连接Kafka读取数据

        Schema schema = new Schema();
        schema.field("id", DataTypes.STRING());
        schema.field("ts", DataTypes.BIGINT());
        schema.field("vc", DataTypes.INT());
        tableEnv.connect(new Kafka()
                .version("universal")
                .topic("sensor")
                .startFromLatest()
                .property(ConsumerConfig.GROUP_ID_CONFIG, "0309")
                .property(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092")
        )
                .withSchema(schema)
                .withFormat(new Json())
                .createTemporaryTable("sensor");

        //4.将表转为Table对象
       /* Table table = tableEnv.from("sensor");

        Table select = table.where($("id").isEqual("sensor_1"))
                .select($("id"), $("ts"), $("vc"));*/

        //将表中数据打印到控制台查看方式
        //a.将表转为流
//        tableEnv.toAppendStream(select, Row.class).print();

        //b.将Table转为TableResult对象直接对其打印
//        TableResult tableResult = select.execute();
//        tableResult.print();

        //c.在有表名的前提下，可以直接写sql返回一个TableResult
        TableResult tableResult = tableEnv.executeSql("select * from sensor where id ='sensor_1'");
        tableResult.print();

//        env.execute();
    }
}
